<?php
/**
 * Created by PhpStorm.
 * User: jochen
 * Date: 2016/10/20
 * Time: 下午6:52
 */

namespace App\Listeners;


use App\Models\Company;
use App\Models\SimCard;
use App\Models\WxClient;
use App\Services\PlatformService;
use App\Services\Repo\WxClientRepo;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Resources\CompanyController;
use App\Plugins\Sms\SendInfo;
use App\Jobs\SendCompanyMessage;

class CompanyObserver
{
    protected $_service;

    function __construct(PlatformService $service)
    {
        $this->_service = $service;
    }

    public function created(Company $company)
    {
        // 创建Group
        $group_id = $this->_service->createGroupByCompany($company);
        // 创建账号
        $userInfo = $company->getInitUserInfo();
        $userInfo['group_id'] = $group_id;
        $alias = $company->getAlias();
        $initUser = new \stdClass();
        list($initUser->user_id, $initUser->password)
            = $this->_service->createUserAccount($company, $userInfo);
        $company->initUser = $initUser;
        $company->save();
        $_filter = [
            'alias' => $alias['alias'],
            'password' => $initUser->password,
            'mobile' => $userInfo['mobile']
        ];
        $job = (new SendCompanyMessage($_filter));
        dispatch($job);
        return "发送短信成功";
    }

    public function updated(Company $company)
    {
        // 保存渠道成功，修改对应的group name
        $orgName = $company->getOriginal('name');
        if ($orgName !== $company->name) {
            $this->_service->updateGroupByCompany($company);
        }
    }
}